package com.zhenjiashi.sideline.cralwer.shixian;

import com.zhenjiashi.sideline.entity.Jobs;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.scheduler.BloomFilterDuplicateRemover;
import us.codecraft.webmagic.scheduler.QueueScheduler;
import us.codecraft.webmagic.selector.Selectable;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class ShixianProcessor implements PageProcessor {

    @Override
    public void process(Page page) {
        List<Selectable> selectables = page.getHtml().css("div.job").nodes();

        List<Jobs> jobs = selectables.stream().map(selectable -> saveInfo(Jsoup.parse(selectable.get()))).collect(Collectors.toList());
        page.putField("jobs", jobs);
    }

    private Jobs saveInfo(Document document) {
        Jobs job = new Jobs();
        job.setCreateTime(new Date());
        job.setPlatform("实现网");

        Element a = document.select("a").first();
        job.setUrl("https://shixian.com" + a.attr("href"));

        Element h5 = a.select("h5.title").first();
        job.setTitle(h5.text());

        Element describe = document.select(".describe").first().parent();
        job.setContent(describe.text());

        Element price = document.select(".price").first();
        job.setPrice(new BigDecimal(price.text().replace(",", "").replace("预估", "").replace("元", "").trim()));

        Element time = document.select(".about").select(".hidden-xs").first().select("dl").first().child(1);
        job.setDays(Long.parseLong(time.text().trim().replace("天", "")));
        job.setPublishTime(job.getCreateTime());

        try {
            Element tags = document.select(".skill-tags").first();
            job.setTags(tags.text());
        } catch (Exception e) {

        }

        return job;
    }

    private Site site = Site
            .me()
            .setCharset("utf-8")
            .setTimeOut(10000)
            .setRetryTimes(3)
            .setSleepTime(3);

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider spider = Spider.create(new ShixianProcessor()).addUrl("https://shixian.com/jobs/part-time");
        spider.setScheduler(new QueueScheduler().setDuplicateRemover(new BloomFilterDuplicateRemover(100000)));
        spider.thread(10);
        spider.run();
    }

}
